// detail.js
var util = require('../../utils/util.js');
var activity_js = require('../../utils/activity.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    view_flag: 1,
    repeatrule : '',
    act_detail: [],
    options: 0,
    activity_detail: '',
    can_modify: true,
    edit: false,
    subscribe_flag: false,
    windowWidth: wx.getSystemInfoSync().windowWidth,
    picturewidth: (wx.getSystemInfoSync().windowWidth - 73) / 4,
    windowHeight: wx.getSystemInfoSync().windowHeight,
    pixelRatio: wx.getSystemInfoSync().pixelRatio,
    join_sheet : [],
    upload_pics: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    //repeattypes: ["仅一次", "每天", "每周", "隔周", "每月"],
    //repeatcounts: ["once", "daily", "weekly", "monthly", "yearly"],
    var repeatrule = new Object();
    repeatrule.once = "仅一次";
    repeatrule.daily = "每天";
    repeatrule.weekly = "每周";
    repeatrule.monthly = "每月";
    repeatrule.yearly = "每年";
    var that = this;
    //调用应用实例的方法获取全局数据
    var app = getApp();
    app.getUserInfo(function (userInfo) {
      //更新数据
      that.setData({
        userInfo: userInfo
      })
    })
    console.log(options);
    var aid = options.id;
    that.setData({
      aid: aid,
      repeatrule: repeatrule,
    });
    

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.refresh_act_detail();
    that.check_subscribe();
  },
  check_subscribe:function () {
    var that = this;
    var aid = that.data.aid;
    activity_js.check_subscribe(aid, function (res){
      console.log(res);
      if (res.data.op == 'activity_check_subscribe') {
        that.refresh_subscribe_flag(res.data.data);
      }
    });
  },
  refresh_subscribe_flag: function (data){
    var that = this;
    console.log(data);
    if (data == null) {
      that.setData({
        subscribe_flag: false
      });
    }else {
      that.setData({
        subscribe_flag: true
      });
    }
  },
  refresh_act_detail: function () {
    var that = this;
    var aid = that.data.aid;
    var repeatrule = that.data.repeatrule;
    console.log('now activity view start... activity :' + aid);
    activity_js.view(aid, function (res) {
      console.log(res);
      if (res.data.op == 'activity_view') {
        var activity_detail = res.data.data.info;
      }
      that.reset_act_detail(activity_detail);
      that.setData({
        edit: res.data.data.editable,
        joined: res.data.data.joined,
        my_joinsheet: res.data.data.join_sheet,
      });
      console.log(activity_detail);
    }); 
  },
  reset_act_detail: function(activity_detail) {
    var that = this; 
    var repeatrule = that.data.repeatrule;
    activity_detail.format_begintime = util.formatDatetime(new Date(activity_detail.begintime * 1000));
    activity_detail.format_endtime = util.formatDatetime(new Date(activity_detail.endtime * 1000));
    activity_detail.format_repeatend = util.formatDatetime(new Date(activity_detail.repeatend * 1000));
    activity_detail.repeatrule = repeatrule[activity_detail.repeattype];
    activity_detail.participants_info = activity_detail.max_participants == 0 ? "不限制" : activity_detail.now_participants + " / " + activity_detail.max_participants;
    that.setData({
      info: activity_detail,
      upload_pics: activity_detail.images_full_list,
      modify_title: activity_detail.title,
      modify_content: activity_detail.content,
      modify_address: activity_detail.address,
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  createwxacodeunlimit: function () {
    var that = this;
    that.setData({
      view_flag: 4
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  },
  share_me: function () {
    console.log('shareMe!');
    wx.showShareMenu({
      withShareTicket: true
    })
  },
  join_it: function (e) {
    var that = this;
    var yuyue_session = wx.getStorageSync("yuyue_session");
    var activity_id = that.data.aid;
    var join_sheet = that.data.join_sheet;
    if (that.data.joined) {
      join_sheet = that.data.my_joinsheet;
    }
    console.log(yuyue_session);
    console.log(activity_id);
    console.log(join_sheet);

    activity_js.sign(activity_id, yuyue_session, join_sheet, function (res) {
      //console.log(res);
      if (res.data.op == 'fail') {
        wx.showModal({
          title: '报名活动失败，编码：' + res.data.code + ",原因：" + res.data.reason,
          showCancel: false
        });
      } else if (res.data.op == 'activity_sign') {
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000
        });
        that.setData({
          joined: true,
          my_joinsheet: join_sheet,
          view_flag: 3
        });
      }
    });
    return false;
  }, 
  cancel_join: function () {
    var that = this;
    var yuyue_session = wx.getStorageSync("yuyue_session");
    var activity_id = that.data.aid;
    if(that.data.joined == false) {
      return false;
    }
    activity_js.unsign(activity_id, yuyue_session, function (res) {
      console.log(res);
      if (res.data.op == 'fail') {
        wx.showModal({
          title: '取消报名失败，编码：' + res.data.code + ",原因：" + res.data.reason,
          showCancel: false
        });
      } else if (res.data.op == 'activity_unsign') {
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000
        });
        that.setData({
          joined: false,
          my_joinsheet: [],
        });
        that.backto_view();
      }
    });
  },
  wanna_join: function () {
    this.setData({
      view_flag: 2
    });
  }, 
  view_my_join_sheet: function () {
    this.setData({
      view_flag: 5
    });
  }, 
  wanna_modify: function () {
    this.setData({
      view_flag: 7
    });
  }, 
  help: function () {
    wx.navigateTo({
      url: '../mine/help/index'
    })
  },
  backto_view: function () {
    this.setData({
      view_flag: 1
    });
  },
  backto_home: function () {
    wx.switchTab({
      url: '../index/index',
    })
  },
  show_pic: function (e){
    var that = this;
    var image_list = that.data.upload_pics;
    var img_preview_list = [];
    for (var i in image_list) {
      img_preview_list.push(image_list[i].image_url);
    }
    var image_url = e.target.dataset.image_url;
    console.log(image_url);
    console.log(image_list);
    wx.previewImage({
      current: image_url, // 当前显示图片的http链接
      urls: img_preview_list // 需要预览的图片http链接列表
    })
  },
  save_image: function () {
    console.log('saveimage...');
    wx.saveImageToPhotosAlbum({
      success(res) {
        console.log(res);
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000
        });
      },
      fail(err) {
        console.log(err);
      }
    });
  },
  input_adata: function (e) {
    var that = this;
    console.log(e);
    var value = e.detail.value;
    var sheet_index = e.target.dataset.sheet_index;
    var join_sheet = that.data.join_sheet;
    join_sheet[sheet_index] = value;
    this.setData({
      join_sheet: join_sheet,
    });
  },  
  input_adata2: function (e) {
    var that = this;
    console.log(e);
    var value = e.detail.value;
    var sheet_index = e.target.dataset.sheet_index;
    var my_join_sheet = that.data.my_joinsheet;
    my_join_sheet[sheet_index] = value;
    this.setData({
      my_joinsheet: my_join_sheet,
    });
  },
  view_join_list: function () {
    var that = this;
    var yuyue_session = wx.getStorageSync("yuyue_session");
    var activity_id = that.data.aid;
    activity_js.view_join_list(activity_id, yuyue_session, function (res) {
      console.log(res);
      if (res.data.op == 'view_join_list') {
        that.setData({
          view_join_list: res.data.data,
          view_flag: 6,
        });
      }
    });
  },
  addPicture: function () {
    var that = this;
    var upload_pictures = that.data.upload_pictures;
    wx.chooseImage({
      count: 9 - that.data.picNum,
      success: function (res) {
        var path = '';
        console.log(res);
        var img_src = res.tempFilePaths[0];
        console.log(img_src);
        activity_js.upload_image(img_src, function (res){
          console.log(res);
          var r = JSON.parse(res.data);
          console.log(r);
          if (r.op == 'upload_image'){
            var name = r.data;
            var pic = new Object();
            pic.name = name;
            pic.image_url = "https://www.xiaoningmengkeji.com/sevsb/upload/images/" + name;
            pic.thumbnail_url = "https://www.xiaoningmengkeji.com/sevsb/upload/thumbnails/thumbnail-" + name;
            var upload_pics = that.data.upload_pics;
            upload_pics.push(pic);
            that.setData({
              upload_pics: upload_pics
            });
          }
        });
        return false;
      }
    })
  },
  removePicture: function (e) {
    var that = this;
    var name = e.target.dataset.name;
    var upload_pics = that.data.upload_pics;
    var return_arr = [];
    for(var i in upload_pics){
      if (upload_pics[i].name == name) {
        upload_pics.splice(i, 1);
        break;
      }
    }
    that.setData({
      upload_pics: upload_pics
    });
  },
  save_modify: function (e) {
    var that = this;
    var aid = that.data.aid;
    var upload_pics = that.data.upload_pics;
    var address = that.data.modify_address;
    var title = e.detail.value.title;
    var content = e.detail.value.content;
    var upload_pic_name_list = [];
    for (var i in upload_pics) {
      upload_pic_name_list.push(upload_pics[i].name);
    }
    console.log(title);
    console.log(content); 
    console.log(upload_pic_name_list);
    
    activity_js.edit(aid, title, content, address, upload_pic_name_list, 0, function (res){
      console.log(res);
      if (res.data.op == 'activity_edit') {
        var activity_detail = res.data.data;
        that.reset_act_detail(activity_detail);
        that.backto_view();
      }
    });
  },
  wanna_cancel: function () {
    var that = this;
    var aid = that.data.aid;
    activity_js.cancel(aid, 0, function (res){
      console.log(res);
      if (res.data.op == 'activity_cancel') {
          var activity_detail = res.data.data;
        }
        that.reset_act_detail(activity_detail);
    });
  }, 
  wanna_start: function () {
    var that = this;
    var aid = that.data.aid;
    activity_js.start(aid, 0, function (res) {
      console.log(res);
      if (res.data.op == 'activity_start') {
        var activity_detail = res.data.data;
      }
      that.reset_act_detail(activity_detail);
    });
  },
  bindPosition: function (e) {
    var that = this;
    var latitude = "";
    var longitude = '';
    var address = '';
    wx.chooseLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function (res) {
        address = res.address;
        console.log("addr:" + latitude + longitude + address);
        that.setData({
          modify_address: address
        })
      },
      fail: function () {
        wx.showModal({
          title: '地点选择失败！请重试',
          showCancel: false
        })
      }
    })
  },
  wanna_unsubcribe: function () {
    var that = this;
    var aid = that.data.aid;
    activity_js.unsubscribe(aid, function (res){
      console.log(res);
      if (res.data.op == 'activity_unsubscribe') {
        that.refresh_subscribe_flag(res.data.data);
      }
    });
  }, 
  wanna_subcribe: function () {
    var that = this; 
    var aid = that.data.aid;
    activity_js.subscribe(aid, function (res) {
      console.log(res);
      if (res.data.op == 'activity_subsrcibe') {
        that.refresh_subscribe_flag(res.data.data);
      }
    });
  },
})